package com.gnerv.author.controller;

import com.gnerv.author.entity.R;
import com.gnerv.author.entity.User;
import com.gnerv.author.service.IUserService;
import com.gnerv.author.util.PasswordUtil;
import com.gnerv.author.util.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Gnerv LiGen
 * @description
 * @data 2019/5/12
 */
@Api(tags = "基础平台-用户登录")
@CrossOrigin
@RestController
@RequestMapping(value = "/blog")
public class LoginController {

    @Autowired
    IUserService userService;

    @ApiOperation(value = "系统登录")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public R login(@RequestBody User user) {
        Subject subject = ShiroUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), PasswordUtil.getEncryptString(user));
        subject.login(token);
        return R.back();
    }

    @ApiOperation(value = "系统退出")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public R logout() {
        ShiroUtils.logout();
        return R.back();
    }

    @RequiresPermissions("blog:login:user")
    @ApiOperation(value = "查询当前登录用户相关信息")
    @RequestMapping(value = "/login/user", method = RequestMethod.GET)
    public R loginUser() {
        User loginUser = ShiroUtils.getLoginUser();
        return R.back().data("loginUser", loginUser);
    }
}
